import Vue from 'vue'
let oldIndex = null
// v-draging: 拖拽属性
/**
 * params
 *    1. index: 当前拖拽进入的元素下标
 *    2. change: change事件 返回oldIndex、newIndex
 *    target子元素添加类名draggable，可以只监听添加了draggable类名的元素
 */
Vue.directive('dragging', {
  bind(el, binding) {
    el.setAttribute('draggable', false)
    const dragTarget = el.querySelectorAll('.draggable')
    const targets = Array.from(dragTarget)
    if (targets.length === 0) {
      el.onmousedown = function(e) {
        el.setAttribute('draggable', true)
      }
    } else {
      targets.forEach(target => {
        target.onmousedown = function(e) {
          el.setAttribute('draggable', true)
        }
      })
    }
    el.ondragstart = () => dragstart(binding.value)
    el.ondragenter = (e) => drag(e, binding.value)
    el.ondragend = () => dragend(el)
  }
})
function onchange(oldIndex, newIndex, change) {
  if (oldIndex === newIndex) return
  if (typeof change === 'function') {
    change(oldIndex, newIndex)
  }
}
function dragstart({ index }) {
  oldIndex = index
}
function drag(e, { index, change }) {
  onchange(oldIndex, index, change)
  oldIndex = index
}
function dragend(el) {
  oldIndex = null
  el.setAttribute('draggable', false)
}
